<script setup lang="ts">
import { h, onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';

import { $t } from '@vben/locales';

import {
  ElButton,
  ElCard,
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElMessage,
  ElOption,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTooltip,
} from 'element-plus';

import {
  getChannelSaleSummeryApi,
  getSalesChannelApi,
  getSuppliersListApi,
} from '#/api';
import CollapsibleCard from '#/components/collapsibleCard.vue';
import CurrentDateTime from '#/components/currentDateTime.vue';
import RaiseStatus from '#/components/raiseStatus.vue';
import {
  getCommonShortcuts,
  getUrlParam,
  mergeDataByLabel,
  updateURLParams,
} from '#/utils';
import { convertToSingleImageAndPrint } from '#/utils/convertAndSplitImage';

const { locale } = useI18n();
const shortcuts = ref(getCommonShortcuts());

watch(locale, () => {
  shortcuts.value = getCommonShortcuts();
});
const submitForm: any = reactive({
  timeRange: [], // 统计日期
  supplierType: true, // 供应商类型
  supplier: [], // 供应商
  salesChannel: [], // 销售渠道
  salesType: '全部', // 销售类型
});

const lastCollectDate = ref<any>(null);

const searchLoading = ref(false);

const onSubmit = async () => {
  if (!submitForm.timeRange[0] || !submitForm.timeRange[1]) {
    ElMessage.warning('请选择统计日期！');
    return;
  }
  try {
    searchLoading.value = true;
    const params = {
      startDate: submitForm.timeRange[0],
      endDate: submitForm.timeRange[1],
      publishernames: submitForm.supplier,
      channelnames: submitForm.salesChannel,
      saletype: submitForm.salesType === '全部' ? '' : submitForm.salesType,
    };
    const { nowData, lastData, systemLastDate } =
      await getChannelSaleSummeryApi(params);
    lastCollectDate.value = systemLastDate;
    const md: any = mergeDataByLabel(nowData, lastData, 'publisherName');
    md.forEach((item: any) => {
      item.cSaleDiscount = `${
        Math.floor((+item.cSaleShiyang / +item.cSaleMayang) * 10_000) / 100
      }`;
      item.lSaleDiscount = `${
        Math.floor((+item.lSaleShiyang / +item.lSaleMayang) * 10_000) / 100
      }`;
      item.cPurchaseDiscount = `${
        Math.floor((+item.cPubCostMoney / +item.cSaleMayang) * 10_000) / 100
      }`;
      item.lPurchaseDiscount = `${
        Math.floor((+item.lPubCostMoney / +item.lSaleMayang) * 10_000) / 100
      }`;
      // 结算毛利 = 实洋 - 预估成本 - 快递 - 平台扣点
      item.cSaleSettlementProfit = `${
        item.cSaleShiyang -
        item.cPubSettMoney -
        item.cExpressMoney -
        item.cPlatformMoney
      }`;
      item.lSaleSettlementProfit = `${
        item.lSaleShiyang -
        item.lPubSettMoney -
        item.lExpressMoney -
        item.lPlatformMoney
      }`;
      item.cSettlementGrossProfitMargin = `${
        Math.floor(
          (+item.cSaleSettlementProfit / Number(item.cSaleShiyang)) * 10_000,
        ) / 100
      }`;
      item.lSettlementGrossProfitMargin = `${
        Math.floor(
          (+item.lSaleSettlementProfit / Number(item.lSaleShiyang)) * 10_000,
        ) / 100
      }`;
    });
    tableData.value = md;
    applyAutoSort();
    updateURLParams({
      _k: JSON.stringify(submitForm),
    });
  } catch (error: any) {
    console.error(error);
  } finally {
    searchLoading.value = false;
  }
  // console.warn(tableData.value);
};

const tableRef = ref<any>(null);

const applyAutoSort = () => {
  const sortBy = getUrlParam('sortBy');
  const sortOrder = getUrlParam('sortOrder');

  if (sortBy && sortOrder) {
    // 设置降序排序
    const columnIndex = tableRef.value?.columns?.findIndex(
      (item: any) => item.property === sortBy,
    );
    const icon = tableRef.value?.$el?.querySelectorAll(`th i.${sortOrder}`)?.[
      columnIndex
    ];
    if (icon) {
      icon.click();
    }
    handleSortChange({ prop: sortBy, order: sortOrder });
  }
};

async function printSection() {
  const w = document
    .querySelector('#printContent4 .el-table__header')
    ?.getBoundingClientRect()?.width;
  await convertToSingleImageAndPrint('#printContent4', `${w}px`);
}

const transNullTarget = (target: any, fixed: boolean = false) => {
  if (!target || `${target}` === 'NaN') {
    return '—';
  }
  if (fixed) {
    return (+target).toFixed(2);
  }
  return target;
};

onMounted(() => {
  getSupplierType();
  getSalesChannelType();
  dealUrlParams();
});

const dealUrlParams = () => {
  if (getUrlParam('_k')) {
    Object.assign(submitForm, JSON.parse(getUrlParam('_k') || '{}'));
    onSubmit();
  }
};

const getSummary = (param: any) => {
  const { columns, data } = param;
  const sums: any[] = [];

  // 需要汇总展示的字段列表
  const summaryFields = new Set([
    'ExpressMoney',
    'PlatformMoney',
    'PubCostMoney',
    'PubSettMoney',
    'PurchaseDiscount',
    'PzNum',
    'SaleDiscount',
    'SaleGrossProfit',
    'SaleGrossProfitMargin',
    'SaleMayang',
    'SaleNum',
    'SaleSettlementProfit',
    'SaleShiyang',
    'SettlementGrossProfitMargin',
  ]);

  columns.forEach((column: any, index: number) => {
    // eslint-disable-next-line unicorn/prefer-string-slice
    const property = column.property.substring(1, column.property.length);

    if (property?.includes('ChannelName')) {
      // 特殊处理 PublisherName 列（只显示标题）
      sums[index] = h('div', { style: { textDecoration: 'underline' } }, [
        $t('views.common.totalCost'),
      ]);
    } else if (summaryFields.has(property)) {
      // 需要汇总的字段统一处理
      const _sum = getColumnSummery(data, property);
      sums[index] = h('div', {}, [
        h('div', { class: 'flex justify-end' }, _sum[0]),
        h(RaiseStatus, {
          // eslint-disable-next-line no-constant-binary-expression
          r1: Number(_sum?.[0]) ?? 0,
          // eslint-disable-next-line no-constant-binary-expression
          r2: Number(_sum?.[1]) ?? 0,
        }),
        h('div', { class: 'flex justify-end' }, _sum[1]),
      ]);
    } else {
      // 其他列留空
      sums[index] = '';
    }
  });

  return sums;
};

const getColumnSummery = (data: any, key: string) => {
  if (data.length === 0) {
    return [0, 0];
  }
  const ck = `c${key}`;
  const lk = `l${key}`;

  let sumC: any = 0;
  let sumL: any = 0;

  data.forEach((item: any) => {
    // 防止字段不存在或不是数字
    const valC = Number(item[ck]) || 0;
    const valL = Number(item[lk]) || 0;

    sumC += valC;
    sumL += valL;
  });
  if (!key.includes('Num')) {
    sumC = sumC.toFixed(2);
    sumL = sumL.toFixed(2);
  }
  return [sumC, sumL];
};

const getSupplierType = async () => {
  const { data } = await getSuppliersListApi();
  options.supplierOptions = data.map((item: any) => ({
    label: item,
    value: item,
  }));
};
const getSalesChannelType = async () => {
  const { data } = await getSalesChannelApi();
  options.salesChannelOptions = data.map((item: any) => ({
    label: item,
    value: item,
  }));
};

const options = reactive<any>({
  supplierOptions: [],
  salesChannelOptions: [],
  salesTypeOptions: [
    {
      label: '全部',
      value: '全部',
    },
    {
      label: '经销',
      value: '经销',
    },
    {
      label: '分销',
      value: '分销',
    },
  ],
});

const tableData = ref<any>([]);

const sortBy = ref('');
const sortOrder = ref('');
const handleSortChange = ({ prop, order }: any) => {
  const ord = order as unknown as string;
  sortBy.value = prop;
  sortOrder.value = ord;
  updateURLParams({
    sortBy: prop,
    sortOrder: order,
  });
  if (!ord) return;
  if (prop === 'cChannelName') {
    tableData.value.sort((a: Record<string, any>, b: Record<string, any>) =>
      ord === 'ascending'
        ? String(a[prop]).localeCompare(String(b[prop]))
        : String(b[prop]).localeCompare(String(a[prop])),
    );
  } else {
    tableData.value.sort((a: Record<string, any>, b: Record<string, any>) =>
      ord === 'ascending'
        ? Number(a[prop]) - Number(b[prop])
        : Number(b[prop]) - Number(a[prop]),
    );
  }
};
const router = useRouter();

const supplierClick = (publisherName: any) => {
  const query = {
    ...submitForm,
    publisherName,
    pageNo: 1,
    pageSize: 20,
  };
  router.push({
    path: '/report/channelSalesDetail',
    query: {
      k: JSON.stringify(query),
    },
  });
};
</script>

<template>
  <!-- 使用 mx-auto 实现左右外边距自动，justify-center 让子元素水平居中 -->
  <div
    class="relative mx-auto flex items-center justify-center space-x-8"
    style="height: calc(100vh - 88px)"
  >
    <!-- 表单区域，隐藏时使用 v-show + transition -->
    <CollapsibleCard>
      <ElForm :model="submitForm" label-position="top" @keyup.enter="onSubmit">
        <ElFormItem :label="$t('views.common.collectDate')">
          <ElDatePicker
            v-model="submitForm.timeRange"
            type="daterange"
            date-format="yyyy-MM-DD"
            value-format="YYYY-MM-DD"
            unlink-panels
            range-separator="-"
            :start-placeholder="$t('views.common.startDate')"
            :end-placeholder="$t('views.common.endDate')"
            :shortcuts="shortcuts"
          />
        </ElFormItem>
        <ElFormItem :label="$t('views.common.supplier')">
          <ElSelect
            v-model="submitForm.supplier"
            multiple
            filterable
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption
              v-for="item in options.supplierOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem :label="$t('views.common.salesChannel')">
          <ElSelect
            v-model="submitForm.salesChannel"
            multiple
            filterable
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption
              v-for="item in options.salesChannelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem :label="$t('views.common.salesType')">
          <ElSelect
            v-model="submitForm.salesType"
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption
              v-for="item in options.salesTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem>
          <div class="flex w-full justify-center">
            <ElButton type="primary" @click="onSubmit">
              {{ $t('views.common.filter') }}
            </ElButton>
            <ElButton @click="printSection">打印</ElButton>
          </div>
        </ElFormItem>
      </ElForm>
    </CollapsibleCard>

    <ElCard class="!ml-1 h-full flex-1 !overflow-auto" id="printContent4">
      <h2 class="my-2 flex items-center justify-center text-base font-bold">
        {{ `${$t('views.report.salesSummaryTitle')}` }}
      </h2>
      <div class="mb-2 flex justify-between text-xs">
        <div class="mr-4 flex justify-end">
          {{ $t('views.report.salesSummaryDesc') }}
        </div>
        <div class="flex justify-end">
          <div class="mr-4">最后数据时间：{{ lastCollectDate }}</div>
          <div class="mr-4">
            {{ $t('views.common.statisticalDate') }}：<span
              v-if="submitForm.timeRange[0] && submitForm.timeRange[1]"
            >
              {{ `${submitForm.timeRange[0]}` }} -
              {{ `${submitForm.timeRange[1]}` }}
            </span>
          </div>
          <CurrentDateTime />
        </div>
      </div>
      <ElTable
        :data="tableData"
        border
        ref="tableRef"
        v-loading="searchLoading"
        :summary-method="getSummary"
        show-summary
        @sort-change="handleSortChange"
      >
        <ElTableColumn
          header-align="center"
          prop="cChannelName"
          :label="$t('views.common.channelType')"
          min-width="100%"
          sortable="custom"
        >
          <template #default="scope">
            <div
              class="text-align-right hover-supplier cursor-pointer !justify-start"
              @click="supplierClick(scope.row.cChannelName)"
            >
              {{ transNullTarget(scope.row.cChannelName) }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          min-width="60%"
          header-align="center"
          prop="cPzNum"
          :label="$t('views.common.totalVariety')"
          sortable="custom"
        >
          <template #default="scope">
            <div class="text-align-right">
              {{ transNullTarget(scope.row.cPzNum) }}
            </div>
            <RaiseStatus :r1="+scope.row.cPzNum" :r2="+scope.row.lPzNum" />
            <div class="text-align-right">
              {{ transNullTarget(scope.row.lPzNum) }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          :label="$t('views.common.totalVolumeNumber')"
          prop="cSaleNum"
          sortable="custom"
        >
          <template #default="scope">
            <div class="text-align-right">
              {{ transNullTarget(scope.row.cSaleNum) }}
            </div>
            <RaiseStatus :r1="+scope.row.cSaleNum" :r2="+scope.row.lSaleNum" />
            <div class="text-align-right">
              {{ transNullTarget(scope.row.lSaleNum) }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          prop="cSaleMayang"
          :label="$t('views.common.totalFixedPrice')"
          sortable="custom"
        >
          <template #default="scope">
            <div class="text-align-right">
              {{ transNullTarget(scope.row.cSaleMayang, true) }}
            </div>
            <RaiseStatus
              :r1="+scope.row.cSaleMayang"
              :r2="+scope.row.lSaleMayang"
            />
            <div class="text-align-right">
              {{ transNullTarget(scope.row.lSaleMayang, true) }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          prop="cSaleShiyang"
          :label="$t('views.common.totalSalePrice')"
          sortable="custom"
        >
          <template #default="scope">
            <div class="text-align-right">
              {{ transNullTarget(scope.row.cSaleShiyang, true) }}
            </div>
            <RaiseStatus
              :r1="+scope.row.cSaleShiyang"
              :r2="+scope.row.lSaleShiyang"
            />
            <div class="text-align-right">
              {{ transNullTarget(scope.row.lSaleShiyang, true) }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          prop="cSaleDiscount"
          :label="$t('views.common.saleDiscount')"
          sortable="custom"
        >
          <template #header="scope">
            <span>
              <ElTooltip
                :aa="scope"
                class="item"
                effect="dark"
                placement="top-start"
              >
                <span class="cursor-pointer">
                  {{ $t('views.common.saleDiscount') }}
                </span>
                <template #content>
                  <div style="width: auto">总实洋/总码洋*100</div>
                </template>
              </ElTooltip>
            </span>
          </template>
          <template #default="scope">
            <div class="text-align-right">
              {{ transNullTarget(scope.row.cSaleDiscount, true) }}
            </div>
            <RaiseStatus
              :r1="+scope.row.cSaleDiscount"
              :r2="+scope.row.lSaleDiscount"
            />
            <div class="text-align-right">
              {{ transNullTarget(scope.row.lSaleDiscount, true) }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          prop="cPubSettMoney"
          :label="$t('views.common.estimatedCost')"
          sortable="custom"
        >
          <template #default="scope">
            <div class="text-align-right">
              {{ transNullTarget(scope.row.cPubSettMoney, true) }}
            </div>
            <RaiseStatus
              :r1="+scope.row.cPubSettMoney"
              :r2="+scope.row.lPubSettMoney"
            />
            <div class="text-align-right">
              {{ transNullTarget(scope.row.lPubSettMoney, true) }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          prop="cExpressMoney"
          :label="$t('views.common.expressDeliveryCost')"
          sortable="custom"
        >
          <template #default="scope">
            <div class="text-align-right">
              {{ transNullTarget(scope.row.cExpressMoney, true) }}
            </div>
            <RaiseStatus
              :r1="+scope.row.cExpressMoney"
              :r2="+scope.row.lExpressMoney"
            />
            <div class="text-align-right">
              {{ transNullTarget(scope.row.lExpressMoney, true) }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          prop="cPlatformMoney"
          :label="$t('views.common.platformDeductionPoints')"
          sortable="custom"
        >
          <template #default="scope">
            <div class="text-align-right">
              {{ transNullTarget(scope.row.cPlatformMoney, true) }}
            </div>
            <RaiseStatus
              :r1="+scope.row.cPlatformMoney"
              :r2="+scope.row.lPlatformMoney"
            />
            <div class="text-align-right">
              {{ transNullTarget(scope.row.lPlatformMoney, true) }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          prop="cSaleSettlementProfit"
          :label="$t('views.common.saleSettlementProfit')"
          sortable="custom"
        >
          <template #header="scope">
            <span>
              <ElTooltip
                :aa="scope"
                class="item"
                effect="dark"
                placement="top-start"
              >
                <span class="cursor-pointer">
                  {{ $t('views.common.saleSettlementProfit') }}
                </span>
                <template #content>
                  <div style="width: auto">
                    实洋 - 预估成本 - 快递成本 - 平台扣点
                  </div>
                </template>
              </ElTooltip>
            </span>
          </template>
          <template #default="scope">
            <div class="text-align-right">
              {{ transNullTarget(scope.row.cSaleSettlementProfit, true) }}
            </div>
            <RaiseStatus
              :r1="+scope.row.cSaleSettlementProfit"
              :r2="+scope.row.lSaleSettlementProfit"
            />
            <div class="text-align-right">
              {{ transNullTarget(scope.row.lSaleSettlementProfit, true) }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          header-align="center"
          prop="cSettlementGrossProfitMargin"
          :label="$t('views.common.settlementGrossProfitMargin')"
          sortable="custom"
        >
          <template #header="scope">
            <span>
              <ElTooltip
                :aa="scope"
                class="item"
                effect="dark"
                placement="top-start"
              >
                <span class="cursor-pointer">
                  {{ $t('views.common.settlementGrossProfitMargin') }}
                </span>
                <template #content>
                  <div style="width: auto">毛利/销售实洋*100</div>
                </template>
              </ElTooltip>
            </span>
          </template>
          <template #default="scope">
            <div class="text-align-right">
              {{
                transNullTarget(scope.row.cSettlementGrossProfitMargin, true)
              }}
            </div>
            <RaiseStatus
              :r1="+scope.row.cSettlementGrossProfitMargin"
              :r2="+scope.row.lSettlementGrossProfitMargin"
            />
            <div class="text-align-right">
              {{
                transNullTarget(scope.row.lSettlementGrossProfitMargin, true)
              }}
            </div>
          </template>
        </ElTableColumn>
      </ElTable>
    </ElCard>
  </div>
</template>

<style scoped>
.text-align-right {
  @apply flex flex-wrap items-center justify-end break-words;
}

:deep(.el-table .cell) {
  padding: 0 8px !important;
}

.hover-supplier:hover {
  color: hsl(var(--primary, 210 100% 50%));
  text-decoration: underline;
  text-underline-offset: 2px; /* 设置下划线距离文字的距离 */
}
</style>
